
package com.kaciula.letsdoit.ui;

import com.kaciula.letsdoit.R;
import com.kaciula.letsdoit.db.WastesDbAdapter;
import com.kaciula.letsdoit.service.LdirWebService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {

    private PreferenceHelper mPrefHelper;

    /* constants */
    private static final int DIALOG_PROGRESS = 0;

    private static final int DIALOG_LOGIN_FAILED = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        mPrefHelper = ((MyApplication) getApplicationContext()).getPrefHelper();

        Button signIn = (Button) findViewById(R.id.sign_in);
        signIn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in:
                EditText usernameView = (EditText) findViewById(R.id.username);
                String username = usernameView.getText().toString();
                EditText passwordView = (EditText) findViewById(R.id.password);
                String password = passwordView.getText().toString();

                new LoginTask().execute(username, password);
                break;
            default:
                break;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_PROGRESS:
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage(getString(R.string.signing_in));
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            case DIALOG_LOGIN_FAILED:
                AlertDialog.Builder builder;
                builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.sign_in);
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setMessage(R.string.invalid_login).setCancelable(false).setPositiveButton(
                        R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog, final int id) {
                                dialog.dismiss();
                            }
                        });
                return builder.create();
            default:
                break;
        }
        return null;
    }

    private class LoginTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            showDialog(DIALOG_PROGRESS);
        }

        @Override
        protected Boolean doInBackground(String... args) {
            String username = args[0];
            String password = args[1];
            String md5Pass = null;
            boolean isValid = false;
            LdirWebService service = new LdirWebService(LoginActivity.this);

            try {
                String salt = service.getUserSalt(username);
                md5Pass = service.generateMd5Pass(password, salt);
                isValid = service.validateUser(username, md5Pass);
            } catch (Throwable e) {
                isValid = false;
            }

            if (isValid) {
                mPrefHelper.saveCredentials(username, password, md5Pass);
            }

            return isValid;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            dismissDialog(DIALOG_PROGRESS);

            if (result == false) {
                showDialog(DIALOG_LOGIN_FAILED);
            } else {
                Toast.makeText(LoginActivity.this, R.string.login_successful, Toast.LENGTH_SHORT)
                        .show();

                Bundle extras = getIntent().getExtras();
                if (extras != null) {
                    long id = extras.getLong(WastesDbAdapter.KEY_ROWID);
                    Intent intent = new Intent();
                    intent.putExtra(WastesDbAdapter.KEY_ROWID, id);
                    setResult(RESULT_OK, intent);
                } else {
                    setResult(RESULT_OK);
                }

                finish();
            }
        }
    }

}
